<template>
	<view class="booking-container">
		<view class="loading" v-if="isLoad === null">
			<text>加载中...</text>
		</view>
		
		<view class="loading" v-if="isLoad === false">
			<text>加载中...</text>
		</view>

		<view v-if="isLoad" class="content">
			<!-- 顶部标题区域 -->
			<view class="header-section">
				<view class="header-card">
					<view class="header-content">
						<view class="header-title">
							<text class="title-text">会议室预约</text>
							<text class="title-subtitle">Meeting Room Booking</text>
						</view>
						<view class="header-icon">📅</view>
					</view>
				</view>
			</view>

			<!-- 预约表单区域 -->
			<view class="form-section">
				<view class="form-card">
					
					<!-- 会议室 -->
					<view class="form-item">
						<view class="form-label">会议室 <text class="required">*</text></view>
						<picker 
							:value="selectedRoomIndex" 
							:range="roomList" 
							range-key="title"
							@change="onRoomChange"
							:disabled="roomList.length === 0"
						>
							<view class="picker-display" :class="{ 'disabled': roomList.length === 0 }">
								<text class="picker-text">{{ selectedRoom.title || (roomList.length === 0 ? '暂无会议室' : '请选择会议室') }}</text>
								<image class="picker-arrow" src="/static/right.png" mode="aspectFit" v-if="roomList.length > 0"></image>
							</view>
						</picker>
					</view>

					<!-- 会议名称 -->
					<view class="form-item">
						<view class="form-label">会议名称 <text class="required">*</text></view>
						<input 
							class="form-input" 
							v-model="formData.meetingName" 
							placeholder="请输入会议名称"
							maxlength="50"
						/>
					</view>

					<!-- 参会人员范围 -->
					<view class="form-item">
						<view class="form-label">参会人员范围 <text class="required">*</text></view>
						<textarea 
							class="form-textarea" 
							v-model="formData.participants" 
							placeholder="请输入参会人员范围，如：技术科全体人员、张三、李四等"
							maxlength="200"
						/>
					</view>

					<!-- 召集人 -->
					<view class="form-item">
						<view class="form-label">召集人 <text class="required">*</text></view>
						<picker 
							:value="selectedConvenerIndex" 
							:range="userList" 
							range-key="displayName"
							@change="onConvenerChange"
							:disabled="userList.length === 0"
						>
							<view class="picker-display" :class="{ 'disabled': userList.length === 0 }">
								<text class="picker-text">{{ selectedConvener.displayName || (userList.length === 0 ? '暂无用户' : '请选择召集人') }}</text>
								<image class="picker-arrow" src="/static/right.png" mode="aspectFit" v-if="userList.length > 0"></image>
							</view>
						</picker>
					</view>

					<!-- 会议日期 -->
					<view class="form-item">
						<view class="form-label">会议日期 <text class="required">*</text></view>
						<view class="picker-display" @click="showDatePicker">
							<text class="picker-text">{{ formatSelectedDate(selectedDate) || '请选择会议日期' }}</text>
							<image class="picker-arrow" src="/static/right.png" mode="aspectFit"></image>
						</view>
					</view>

					<!-- 会议时间 -->
					<view class="form-item">
						<view class="form-label">会议时间 <text class="required">*</text></view>
						<view class="time-picker-container">
							<!-- 开始时间 -->
							<view class="time-picker-item">
								<view class="picker-label">开始时间</view>
								<picker 
									mode="time" 
									:value="selectedTimeRange.start" 
									start="08:30" 
									end="20:30" 
									@change="onStartTimeChange"
								>
									<view class="picker-display">
										<text class="picker-text" :class="{ 'placeholder': !selectedTimeRange.start }">{{ selectedTimeRange.start || '请选择开始时间' }}</text>
										<image class="picker-arrow" src="/static/right.png" mode="aspectFit"></image>
									</view>
								</picker>
							</view>
							
							<!-- 结束时间 -->
							<view class="time-picker-item">
								<view class="picker-label">结束时间</view>
								<picker 
									mode="time" 
									:value="selectedTimeRange.end" 
									:start="selectedTimeRange.start || '08:30'" 
									end="21:00" 
									@change="onEndTimeChange"
								>
									<view class="picker-display">
										<text class="picker-text" :class="{ 'placeholder': !selectedTimeRange.end }">{{ selectedTimeRange.end || '请选择结束时间' }}</text>
										<image class="picker-arrow" src="/static/right.png" mode="aspectFit"></image>
									</view>
								</picker>
							</view>
						</view>
					</view>

					<!-- 预约人 -->
					<view class="form-item">
						<view class="form-label">预约人 <text class="required">*</text></view>
						<view class="form-display">
							<text class="display-text">{{ currentUser.displayName || '加载中...' }}</text>
						</view>
					</view>

					<!-- 科室 -->
					<view class="form-item">
						<view class="form-label">科室 <text class="required">*</text></view>
						<view class="form-display">
							<text class="display-text">{{ currentUser.deptName || '加载中...' }}</text>
						</view>
					</view>

					<!-- 是否需要会议保障 -->
					<view class="form-item">
						<view class="form-label">是否需要会议保障</view>
						<view class="support-hint">是否需要技术人员在现场提供会议支持</view>
						<view class="support-options">
							<view class="support-option" 
								:class="{ active: formData.meetingSupport === 'yes' }"
								@click="selectMeetingSupport('yes')"
							>
								<view class="option-content">
									<text class="option-title">需要</text>
								</view>
								<view class="option-check" v-if="formData.meetingSupport === 'yes'">
									<image src="/static/selected.png" mode="aspectFit"></image>
								</view>
							</view>
							<view class="support-option" 
								:class="{ active: formData.meetingSupport === 'no' }"
								@click="selectMeetingSupport('no')"
							>
								<view class="option-content">
									<text class="option-title">不需要</text>
								</view>
								<view class="option-check" v-if="formData.meetingSupport === 'no'">
									<image src="/static/selected.png" mode="aspectFit"></image>
								</view>
							</view>
						</view>
					</view>

					<!-- 是否到分局 -->
					<view class="form-item">
						<view class="form-label">是否到分局</view>
						<view class="support-hint">是否需要连线分局进行会议</view>
						<view class="support-options">
							<view class="support-option" 
								:class="{ active: formData.need_branch_office === 'yes' }"
								@click="selectneed_branch_office('yes')"
							>
								<view class="option-content">
									<text class="option-title">是</text>
								</view>
								<view class="option-check" v-if="formData.need_branch_office === 'yes'">
									<image src="/static/selected.png" mode="aspectFit"></image>
								</view>
							</view>
							<view class="support-option" 
								:class="{ active: formData.need_branch_office === 'no' }"
								@click="selectneed_branch_office('no')"
							>
								<view class="option-content">
									<text class="option-title">否</text>
								</view>
								<view class="option-check" v-if="formData.need_branch_office === 'no'">
									<image src="/static/selected.png" mode="aspectFit"></image>
								</view>
							</view>
						</view>
					</view>

					<!-- 选择分局（多选） -->
					<view class="form-item" v-if="formData.need_branch_office === 'yes'">
						<view class="form-label">选择分局 <text class="required">*</text></view>
						<!-- 全选按钮 -->
						<view class="select-all-container">
							<view 
								class="select-all-btn" 
								:class="{ active: isAllBranchesSelected }"
								@click="toggleSelectAll"
							>
								<view class="option-content">
									<text class="option-title">全选</text>
								</view>
								<view class="option-check" v-if="isAllBranchesSelected">
									<image src="/static/selected.png" mode="aspectFit"></image>
								</view>
							</view>
						</view>
						<view class="branch-options">
							<view 
								class="branch-option" 
								v-for="(branch, index) in branchOfficeList" 
								:key="index"
								:class="{ active: isBranchSelected(branch) }"
								@click="toggleBranch(branch)"
							>
								<view class="option-content">
									<text class="option-title">{{ branch }}</text>
								</view>
								<view class="option-check" v-if="isBranchSelected(branch)">
									<image src="/static/selected.png" mode="aspectFit"></image>
								</view>
							</view>
						</view>
					</view>

					<!-- 备注 -->
					<view class="form-item">
						<view class="form-label">备注</view>
						<textarea 
							class="form-textarea" 
							v-model="formData.remark" 
							placeholder="请输入备注信息（可选）"
							maxlength="500"
						/>
					</view>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-section">
				<view class="action-buttons">
					<view class="action-btn secondary" @click="goBack">
						<text class="btn-text">返回</text>
					</view>
					<view class="action-btn primary" @click="submitBooking">
						<text class="btn-text">确认预约</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 日期选择弹窗 -->
		<view class="modal-overlay" v-if="showDateModal" @click="hideDatePicker" @touchmove.stop.prevent="preventTouchMove" @touchstart.stop>
			<view class="modal-content" @click.stop @touchmove.stop>
				<view class="modal-header">
					<text class="modal-title">选择会议日期</text>
					<text class="modal-close" @click="hideDatePicker">×</text>
				</view>
				<view class="modal-body">
					<!-- 月份选择器 -->
					<view class="month-selector">
						<view class="arrow-btn" @click="prevMonth">
							<image class="arrow" src="/static/right.png" mode="aspectFit" style="transform: rotate(180deg);"></image>
						</view>
						<view class="current-month">
							<text class="month-text">{{ currentYear }}年{{ currentMonth }}月</text>
						</view>
						<view class="arrow-btn" @click="nextMonth">
							<image class="arrow" src="/static/right.png" mode="aspectFit"></image>
						</view>
						<view class="today-btn" @click="goToToday">
							<text>今天</text>
						</view>
					</view>
					
					<!-- 日期选择区域 -->
					<view class="date-selector" v-if="currentMonth">
						<view class="weekdays-header">
							<view class="weekday" v-for="day in weekdays" :key="day">{{ day }}</view>
						</view>
						<view class="calendar-grid">
							<view class="calendar-day" 
								v-for="(day, dayIndex) in currentMonthDays" 
								:key="dayIndex"
								:class="{ 
									'other-month': !day.currentMonth,
									'today': day.isToday,
									'selected': tempSelectedDate === day.value,
									'disabled': day.disabled
								}"
								@click="selectDate(day)"
							>
								<view class="day-number">{{ day.day }}</view>
								<view class="today-dot" v-if="day.isToday"></view>
							</view>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<view class="modal-btn" @click="hideDatePicker">取消</view>
					<view class="modal-btn primary" @click="confirmDateSelection">确定</view>
				</view>
			</view>
		</view>


	</view>
</template>

<script>
import api, { handleApiError } from '@/utils/api.js'

export default {
	data() {
		return {
			isLoad: true,
			isLoadTime: true,
			selectedDate: '',
			selectedTimeRange: {
				start: '',
				end: ''
			},
			currentDateDisplay: '',
			showDateModal: false,
			tempSelectedDate: '',
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth() + 1,
			weekdays: ['日', '一', '二', '三', '四', '五', '六'],
			currentMonthDays: [],
			enroll: {
				_id: '1',
				ENROLL_TITLE: '会议室A',
				ENROLL_CATE_NAME: '中型会议室',
				ENROLL_OBJ: {
					person: '15人',
					tools: ['投影仪', '白板', '音响', '视频会议']
				}
			},
			roomList: [],
			selectedRoomIndex: 0,
			selectedRoom: {},
			presetRoomTitle: '', // 预设的会议室标题
			presetRoomId: null, // 预设的会议室ID
			userList: [],
			selectedConvenerIndex: 0,
			selectedConvener: {},
			currentUser: {
				userId: '',
				userName: '',
				nickName: '',
				deptName: '',
				displayName: ''
			},
			dateList: [],
			formData: {
				meetingName: '',
				participants: '',
				meetingSupport: 'no',
				need_branch_office: 'no',
				selected_branches: [],
				remark: ''
			},
			branchOfficeList: ['市中区', '薛城区', '峄城区', '台儿庄区', '山亭区', '滕州市', '高新区'],
			editId: null, // 编辑模式下的预约ID
			isEditMode: false, // 是否为编辑模式
			scrollTop: 0 // 记录页面滚动位置，用于iOS滚动穿透修复
		}
	},
	async onLoad(options) {
		// 先检查是否为编辑模式，以便在加载用户列表时知道是否需要设置默认召集人
		if (options && options.editId) {
			this.editId = options.editId;
			this.isEditMode = true;
		}
		
		// 先处理传参，设置预设的会议室ID（需要在加载会议室列表之前设置）
		if (options && options.id) {
			// 根据ID加载会议室详情
			this.loadEnrollDetail(options.id);
			// 同时将id作为会议室ID，用于自动选中会议室
			this.presetRoomId = options.id;
		}
		if (options && options.title) {
			// 设置默认会议室
			this.presetRoomTitle = decodeURIComponent(options.title);
		}
		if (options && options.roomId) {
			// 编辑模式时，设置默认会议室
			this.presetRoomId = options.roomId;
		}
		
		// 加载当前用户信息
		await this.loadCurrentUser();
		// 加载会议室列表（此时presetRoomId已设置，会自动选中）
		await this.loadRoomList();
		// 加载用户列表（用于召集人选择）
		await this.loadUserList();
		
		// 如果是编辑模式，加载预约详情
		if (this.isEditMode && this.editId) {
			// 加载预约详情
			await this.loadBookingDetail(this.editId);
		}
		// 初始化日期列表（先初始化，避免覆盖传入的日期）
		this.initDateList();
		
		// 如果从URL参数传入了日期，设置日期（需要在initDateList之后设置）
		if (options && options.date) {
			// 从日历页面传递过来的日期
			this.selectedDate = options.date;
			this.tempSelectedDate = options.date;
			// 根据传入的日期设置当前年月，并重新生成日历
			const [year, month] = options.date.split('-');
			this.currentYear = parseInt(year);
			this.currentMonth = parseInt(month);
			this.generateMonthDays();
		}
	},
	computed: {
		// 判断是否所有分局都已选中
		isAllBranchesSelected() {
			return this.branchOfficeList.length > 0 && 
				   this.formData.selected_branches.length === this.branchOfficeList.length;
		}
	},
	mounted() {
		// 确保默认选中今天（如果没有从参数中传入日期）
		if (!this.selectedDate) {
			const today = new Date();
			const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
			this.selectedDate = todayStr;
			this.tempSelectedDate = todayStr;
		}
	},
	methods: {
		// 加载预约详情（编辑模式）
		async loadBookingDetail(bookingId) {
			if (!bookingId) {
				uni.showToast({
					title: '预约ID不能为空',
					icon: 'none'
				});
				return;
			}
			
			try {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				
				// 使用 system/yuyue/${id} 接口获取预约详情
				const response = await api.getYuyue(bookingId);
				uni.hideLoading();
				
				if (response && response.code === 200 && response.data) {
					const booking = response.data;
					
					// 填充表单数据
					this.formData.meetingName = booking.meetingtitle || '';
					this.formData.participants = booking.content || '';
					this.formData.meetingSupport = booking.ensure === 1 ? 'yes' : 'no';
					this.formData.need_branch_office = booking.need_branch_office === 1 ? 'yes' : 'no';
					// 加载分局信息（如果有）
					if (booking.selected_branches) {
						this.formData.selected_branches = booking.selected_branches.split(',').filter(b => b.trim());
					} else {
						this.formData.selected_branches = [];
					}
					this.formData.remark = booking.remark || '';
					
					// 设置日期
					if (booking.thedate) {
						this.selectedDate = booking.thedate;
						this.tempSelectedDate = booking.thedate;
					}
					
					// 设置时间范围
					if (booking.startTime && booking.endTime) {
						this.selectedTimeRange = {
							start: booking.startTime,
							end: booking.endTime
						};
					}
					
					// 设置会议室（等待会议室列表加载完成）
					if (booking.pid) {
						this.presetRoomId = booking.pid;
						// 延迟设置，确保会议室列表已加载
						this.$nextTick(() => {
							if (this.roomList.length > 0) {
								this.selectRoomById(booking.pid);
							} else {
								// 如果会议室列表还未加载，等待加载完成
								setTimeout(() => {
									this.selectRoomById(booking.pid);
								}, 300);
							}
						});
					}
					
					// 设置召集人（等待用户列表加载完成）
					if (booking.convener) {
						this.$nextTick(() => {
							if (this.userList.length > 0) {
								this.selectConvenerById(booking.convener);
							} else {
								// 如果用户列表还未加载，等待加载完成
								setTimeout(() => {
									this.selectConvenerById(booking.convener);
								}, 300);
							}
						});
					}
				} else {
					uni.showToast({
						title: response?.msg || '加载预约详情失败',
						icon: 'none',
						duration: 2000
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('加载预约详情错误:', error);
				handleApiError(error);
			}
		},
		
		// 根据ID选择会议室
		selectRoomById(roomId) {
			if (!roomId || this.roomList.length === 0) {
				return;
			}
			// 支持字符串和数字类型的ID匹配
			const room = this.roomList.find(r => {
				return r.id == roomId || String(r.id) === String(roomId);
			});
			if (room) {
				const index = this.roomList.indexOf(room);
				this.selectedRoomIndex = index;
				this.selectedRoom = {
					id: room.id,
					title: room.title || '未知会议室'
				};
			} else {
				console.warn('未找到ID为', roomId, '的会议室');
			}
		},
		
		// 根据ID选择召集人
		selectConvenerById(userId) {
			const user = this.userList.find(u => u.userId === userId);
			if (user) {
				const index = this.userList.indexOf(user);
				this.selectedConvenerIndex = index;
				this.selectedConvener = user;
			}
		},
		
		// 加载当前用户信息
		async loadCurrentUser() {
			try {
				// 先从本地存储读取用户信息
				const storedUserInfo = uni.getStorageSync('userInfo');
				if (storedUserInfo) {
					this.currentUser = {
						userId: storedUserInfo.userId,
						userName: storedUserInfo.userName || storedUserInfo.username,
						nickName: storedUserInfo.nickName || storedUserInfo.nickname,
						deptName: storedUserInfo.deptName || storedUserInfo.department || '未知部门',
						department: storedUserInfo.department,
						displayName: storedUserInfo.nickName || storedUserInfo.nickname || storedUserInfo.userName || storedUserInfo.username
					};
				}
				
				// 从接口获取最新用户信息
				const response = await api.getUserInfo();
				if (response && response.code === 200) {
					const user = response.user;
					this.currentUser = {
						userId: user.userId,
						userName: user.userName,
						nickName: user.nickName,
						deptName: user.dept?.deptName || '未知部门',
						displayName: user.nickName || user.userName,
						department: user.dept?.deptId || ''
					};
					// 更新本地存储
					uni.setStorageSync('userInfo', {
						userId: this.currentUser.userId,
						userName: this.currentUser.userName,
						nickName: this.currentUser.nickName,
						deptName: this.currentUser.deptName,
						department: this.currentUser.department
					});
				}
			} catch (error) {
				console.error('获取当前用户信息错误:', error);
				// 如果接口失败，保持本地存储的信息
			}
		},
		
		// 加载会议室列表
		async loadRoomList() {
			this.isLoad = false
			uni.showLoading({
				title: '加载中...'
			})
			
			try {
				const response = await api.getRoomList()
				uni.hideLoading()
				this.isLoad = true
				
				if (response && response.code === 200) {
					const rooms = response.rows || response.data || []
				// 转换数据格式以适配现有组件
				this.roomList = rooms.map(room => {
					let title = room.roomName || room.name || room.ENROLL_TITLE || room.title
					// 如果room.name包含"1楼"或者"一楼"，在title后添加提示
					if (room.name && (room.name.includes('1楼') || room.name.includes('一楼'))) {
						title = room.name + '(请与支队综合科确认)'
					}
					return {
						id: room.roomId || room.id || room._id,
						title: title,
						category: room.category || room.ENROLL_CATE_NAME || '会议室',
						capacity: room.capacity || room.person || '未知',
						tools: room.tools || room.ENROLL_OBJ?.tools || [],
						location: room.location || room.description || room.desc || room.remark || ''
					}
				})
					
					// 初始化会议室选择
					this.initRoomSelection()
					
					// 如果有预设的会议室ID（编辑模式），设置会议室
					if (this.presetRoomId) {
						this.$nextTick(() => {
							this.selectRoomById(this.presetRoomId);
						});
					}
				} else {
					uni.showToast({
						title: response.msg || '获取会议室列表失败',
						icon: 'none'
					})
					this.isLoad = true
				}
			} catch (error) {
				uni.hideLoading()
				this.isLoad = true
				handleApiError(error)
			}
		},
		
		// 加载用户列表
		async loadUserList() {
			try {
				const response = await api.getUserList()
				
				if (response && response.code === 200) {
					const users = response.rows || []
					// 转换数据格式以适配现有组件
					this.userList = users.map(user => ({
						userId: user.userId,
						userName: user.userName,
						nickName: user.nickName,
						deptName: user.dept?.deptName || '未知部门',
						displayName: user.nickName,
						phone: user.phonenumber || '',
						email: user.email || ''
					}))
					
					// 初始化召集人选择
					this.initConvenerSelection()
				} else {
					console.error('获取用户列表失败:', response.msg)
				}
			} catch (error) {
				console.error('获取用户列表错误:', error)
			}
		},
		
		loadEnrollDetail(id) {
			// 模拟加载会议室详情
			console.log('加载会议室详情:', id);
		},
		
		initRoomSelection() {
			// 默认选择第一个会议室
			if (this.roomList.length > 0) {
				this.selectedRoomIndex = 0;
				this.selectedRoom = this.roomList[0];
				
				// 如果有预设的会议室标题，尝试匹配
				if (this.presetRoomTitle) {
					const roomIndex = this.roomList.findIndex(room => room.title === this.presetRoomTitle);
					if (roomIndex !== -1) {
						this.selectedRoomIndex = roomIndex;
						this.selectedRoom = this.roomList[roomIndex];
					}
				}
			}
		},
		
		initConvenerSelection() {
			// 如果是编辑模式（存在 editId），不设置默认召集人，等待 loadBookingDetail 加载
			if (this.editId) {
				return;
			}
			
			// 默认选择当前用户作为召集人
			if (this.userList.length > 0) {
				// 尝试找到当前用户
				if (this.currentUser && this.currentUser.userId) {
					const currentUserIndex = this.userList.findIndex(user => user.userId === this.currentUser.userId);
					if (currentUserIndex !== -1) {
						// 找到当前用户，设置为默认召集人
						this.selectedConvenerIndex = currentUserIndex;
						this.selectedConvener = this.userList[currentUserIndex];
						return;
					}
				}
				// 如果找不到当前用户，则使用第一个用户作为默认值
				this.selectedConvenerIndex = 0;
				this.selectedConvener = this.userList[0];
			}
		},
		
		onRoomChange(e) {
			const index = e.detail.value;
			this.selectedRoomIndex = index;
			this.selectedRoom = this.roomList[index];
		},
		
		onConvenerChange(e) {
			const index = e.detail.value;
			this.selectedConvenerIndex = index;
			this.selectedConvener = this.userList[index];
		},
		initDateList() {
			// 如果没有设置日期，默认选中今天的日期
			if (!this.selectedDate) {
				const today = new Date();
				const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
				this.selectedDate = todayStr;
				this.tempSelectedDate = todayStr;
			}
			
			// 如果已有选中的日期，根据该日期设置当前年月
			if (this.selectedDate) {
				const [year, month] = this.selectedDate.split('-');
				this.currentYear = parseInt(year);
				this.currentMonth = parseInt(month);
			}
			
			// 生成当前月份的日历
			this.generateMonthDays();
		},
		generateMonthDays() {
			const year = this.currentYear;
			const month = this.currentMonth;
			const firstDay = new Date(year, month - 1, 1);
			const lastDay = new Date(year, month, 0);
			const today = new Date();
			
			const days = [];
			
			// 获取上个月的最后几天
			const firstDayOfWeek = firstDay.getDay();
			const prevMonth = new Date(year, month - 1, 0);
			for (let i = firstDayOfWeek - 1; i >= 0; i--) {
				const day = new Date(year, month - 1, -i);
				days.push({
					day: day.getDate(),
					value: `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`,
					currentMonth: false,
					isToday: this.isSameDay(day, today),
					disabled: this.isBeforeToday(day)
				});
			}
			
			// 当前月的天数
			for (let i = 1; i <= lastDay.getDate(); i++) {
				const day = new Date(year, month - 1, i);
				days.push({
					day: i,
					value: `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`,
					currentMonth: true,
					isToday: this.isSameDay(day, today),
					disabled: this.isBeforeToday(day)
				});
			}
			
			// 下个月的前几天
			const remainingDays = 42 - days.length; // 保持6行
			for (let i = 1; i <= remainingDays; i++) {
				const day = new Date(year, month, i);
				days.push({
					day: i,
					value: `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`,
					currentMonth: false,
					isToday: this.isSameDay(day, today),
					disabled: this.isBeforeToday(day)
				});
			}
			
			this.currentMonthDays = days;
		},
		
		isSameDay(date1, date2) {
			return date1.getFullYear() === date2.getFullYear() &&
				   date1.getMonth() === date2.getMonth() &&
				   date1.getDate() === date2.getDate();
		},
		
		isBeforeToday(date) {
			const today = new Date();
			today.setHours(0, 0, 0, 0);
			date.setHours(0, 0, 0, 0);
			return date < today;
		},
		
		formatSelectedDate(dateStr) {
			if (!dateStr) return '';
			const dateParts = dateStr.split('-');
			if (dateParts.length === 3) {
				const year = dateParts[0];
				const month = parseInt(dateParts[1]);
				const day = parseInt(dateParts[2]);
				return `${year}年${month}月${day}日`;
			}
			return dateStr;
		},
		
		onStartTimeChange(e) {
			this.selectedTimeRange.start = e.detail.value;
			// 如果结束时间早于开始时间，清空结束时间
			if (this.selectedTimeRange.end && this.timeToMinutes(this.selectedTimeRange.end) <= this.timeToMinutes(this.selectedTimeRange.start)) {
				this.selectedTimeRange.end = '';
			}
		},
		
		onEndTimeChange(e) {
			this.selectedTimeRange.end = e.detail.value;
		},
		
		timeToMinutes(timeStr) {
			if (!timeStr) return 0;
			const [hours, minutes] = timeStr.split(':').map(Number);
			return hours * 60 + minutes;
		},
		
		selectMeetingSupport(value) {
			this.formData.meetingSupport = value;
		},
		
		selectneed_branch_office(value) {
			this.formData.need_branch_office = value;
			// 如果选择"否"，清空已选分局
			if (value === 'no') {
				this.formData.selected_branches = [];
			}
		},
		
		toggleBranch(branch) {
			const index = this.formData.selected_branches.indexOf(branch);
			if (index > -1) {
				// 如果已选中，则取消选择
				this.formData.selected_branches.splice(index, 1);
			} else {
				// 如果未选中，则添加
				this.formData.selected_branches.push(branch);
			}
		},
		
		isBranchSelected(branch) {
			return this.formData.selected_branches.indexOf(branch) > -1;
		},
		
		toggleSelectAll() {
			if (this.isAllBranchesSelected) {
				// 如果全部已选中，则取消全选
				this.formData.selected_branches = [];
			} else {
				// 如果未全部选中，则全选
				this.formData.selected_branches = [...this.branchOfficeList];
			}
		},
		
		// 阻止背景滚动（iOS专用）
		preventTouchMove(e) {
			e.preventDefault();
			e.stopPropagation();
			return false;
		},
		
		// 允许内容区域滚动
		allowTouchMove(e) {
			// 允许内容区域内部滚动，不阻止事件
			// 事件已经在模板中通过 @touchmove.stop 处理
		},

		showDatePicker() {
			this.tempSelectedDate = this.selectedDate;
			// 确保当前月份与已选择的日期匹配
			if (this.selectedDate) {
				const [year, month] = this.selectedDate.split('-');
				this.currentYear = parseInt(year);
				this.currentMonth = parseInt(month);
				this.generateMonthDays();
			}
			
			// iOS滚动穿透修复：记录当前滚动位置
			uni.createSelectorQuery().selectViewport().scrollOffset((res) => {
				this.scrollTop = res.scrollTop || 0;
			}).exec();
			
			this.showDateModal = true;
			
			// 阻止页面滚动穿透 - 固定页面（兼容H5和uni-app）
			this.$nextTick(() => {
				// #ifdef H5
				if (typeof document !== 'undefined') {
					const html = document.documentElement;
					const body = document.body;
					this.scrollTop = window.pageYOffset || html.scrollTop || body.scrollTop || 0;
					
					// 固定页面位置
					html.style.overflow = 'hidden';
					html.style.position = 'fixed';
					html.style.width = '100%';
					html.style.top = `-${this.scrollTop}px`;
					
					body.style.overflow = 'hidden';
					body.style.position = 'fixed';
					body.style.width = '100%';
					body.style.top = `-${this.scrollTop}px`;
				}
				// #endif
			});
		},
		hideDatePicker() {
			this.showDateModal = false;
			
			// iOS滚动穿透修复：恢复页面滚动
			this.$nextTick(() => {
				// #ifdef H5
				if (typeof document !== 'undefined') {
					const html = document.documentElement;
					const body = document.body;
					
					// 恢复页面样式
					html.style.overflow = '';
					html.style.position = '';
					html.style.width = '';
					html.style.top = '';
					
					body.style.overflow = '';
					body.style.position = '';
					body.style.width = '';
					body.style.top = '';
					
					// 恢复滚动位置
					if (this.scrollTop > 0) {
						window.scrollTo(0, this.scrollTop);
					}
				}
				// #endif
				
				// uni-app方式恢复滚动位置
				if (this.scrollTop > 0) {
					uni.pageScrollTo({
						scrollTop: this.scrollTop,
						duration: 0
					});
				}
			});
		},

		prevMonth() {
			if (this.currentMonth === 1) {
				this.currentYear--;
				this.currentMonth = 12;
			} else {
				this.currentMonth--;
			}
			this.generateMonthDays();
		},
		
		nextMonth() {
			if (this.currentMonth === 12) {
				this.currentYear++;
				this.currentMonth = 1;
			} else {
				this.currentMonth++;
			}
			this.generateMonthDays();
		},
		
		goToToday() {
			const today = new Date();
			this.currentYear = today.getFullYear();
			this.currentMonth = today.getMonth() + 1;
			// 设置临时选中为今天，确保高亮
			const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
			this.tempSelectedDate = todayStr;
			this.generateMonthDays();
		},
		
		selectDate(day) {
			if (day.disabled) {
				uni.showToast({
					title: '不能选择过去的日期',
					icon: 'none'
				});
				return;
			}
			this.tempSelectedDate = day.value;
		},

		confirmDateSelection() {
			this.selectedDate = this.tempSelectedDate;
			this.selectedTimeRange = { start: '', end: '' }; // 切换日期时清空已选时间范围
			this.hideDatePicker();
		},

		goBack() {
			uni.navigateBack();
		},
		validateForm() {
			if (!this.formData.meetingName.trim()) {
				uni.showToast({
					title: '请输入会议名称',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.participants.trim()) {
				uni.showToast({
					title: '请输入参会人员范围',
					icon: 'none'
				});
				return false;
			}
			if (!this.selectedConvener.userName || this.userList.length === 0) {
				uni.showToast({
					title: this.userList.length === 0 ? '暂无可用用户' : '请选择召集人',
					icon: 'none'
				});
				return false;
			}
			if (!this.selectedDate) {
				uni.showToast({
					title: '请选择会议日期',
					icon: 'none'
				});
				return false;
			}
			if (!this.selectedTimeRange.start || !this.selectedTimeRange.end) {
				uni.showToast({
					title: '请选择会议时间范围',
					icon: 'none'
				});
				return false;
			}
			if (!this.currentUser.userName) {
				uni.showToast({
					title: '获取当前用户信息失败，请重新登录',
					icon: 'none'
				});
				return false;
			}
			if (!this.selectedRoom.id || this.roomList.length === 0) {
				uni.showToast({
					title: this.roomList.length === 0 ? '暂无可用会议室' : '请选择会议室',
					icon: 'none'
				});
				return false;
			}
			// 如果选择到分局，必须至少选择一个分局
			if (this.formData.need_branch_office === 'yes' && this.formData.selected_branches.length === 0) {
				uni.showToast({
					title: '请至少选择一个分局',
					icon: 'none'
				});
				return false;
			}
			return true;
		},
		formatTime(timeStr) {
			return timeStr || '';
		},
		
		// 检查时间段冲突
		async checkTimeConflict() {
			if (!this.selectedDate || !this.selectedTimeRange.start || !this.selectedTimeRange.end || !this.selectedRoom.id) {
				return null;
			}
			
			try {
				// 调用接口查询该日期该会议室的所有预约
				const response = await api.getMeetingsByDate(this.selectedDate, {
					pageNum: 1,
					pageSize: 999,
					orderByColumn: 'id',
					isAsc: 'desc',
					pid: this.selectedRoom.id // 按会议室ID筛选
				});
				
				if (response && response.code === 200) {
					const meetings = response.rows || [];
					
					// 如果是编辑模式，排除当前预约本身
					const existingMeetings = this.isEditMode && this.editId 
						? meetings.filter(m => m.id != this.editId)
						: meetings;
					
					// 只检查已通过（state=2）的预约，已取消（state=4）和拒绝（state=3）的不算冲突
					const validMeetings = existingMeetings.filter(m => m.state == '2');
					
					// 将时间转换为分钟数进行比较
					const newStartMinutes = this.timeToMinutes(this.selectedTimeRange.start);
					const newEndMinutes = this.timeToMinutes(this.selectedTimeRange.end);
					
					// 检查是否有时间冲突
					for (let meeting of validMeetings) {
						if (!meeting.startTime || !meeting.endTime) continue;
						
						const existingStartMinutes = this.timeToMinutes(meeting.startTime);
						const existingEndMinutes = this.timeToMinutes(meeting.endTime);
						
						// 判断时间段是否重叠
						// 冲突条件：新预约的开始时间在已有预约的时间段内，或者新预约的结束时间在已有预约的时间段内，或者新预约完全包含已有预约
						if ((newStartMinutes >= existingStartMinutes && newStartMinutes < existingEndMinutes) ||
							(newEndMinutes > existingStartMinutes && newEndMinutes <= existingEndMinutes) ||
							(newStartMinutes <= existingStartMinutes && newEndMinutes >= existingEndMinutes)) {
							return {
								conflict: true,
								meeting: meeting
							};
						}
					}
					
					return { conflict: false };
				}
				
				return null;
			} catch (error) {
				console.error('检查时间冲突错误:', error);
				// 如果检查失败，不阻止提交，但记录错误
				return null;
			}
		},
		
		async submitBooking() {
			if (!this.validateForm()) {
				return;
			}
			
			// 检查时间段冲突
			uni.showLoading({
				title: '检查中...',
				mask: true
			});
			
			const conflictResult = await this.checkTimeConflict();
			uni.hideLoading();
			
			if (conflictResult && conflictResult.conflict) {
				const conflictMeeting = conflictResult.meeting;
				const conflictTime = `${conflictMeeting.startTime} - ${conflictMeeting.endTime}`;
				uni.showModal({
					title: '时间冲突',
					content: `该时间段与已有预约冲突：\n${conflictTime}\n请选择其他时间段`,
					showCancel: false,
					confirmText: '我知道了'
				});
				return;
			}
			
			// 按照新的字段名称构建预约数据
			const bookingData = {
				meetingtitle: this.formData.meetingName,
				pid: this.selectedRoom.id,
				convener: this.selectedConvener.userId, // 使用用户ID
				thedate: this.selectedDate,
				startTime: this.selectedTimeRange.start,
				endTime: this.selectedTimeRange.end,
				content: this.formData.participants,
				ensure: this.formData.meetingSupport === 'yes' ? 1 : 0,
				need_branch_office: this.formData.need_branch_office === 'yes' ? 1 : 0,
				selected_branches: this.formData.need_branch_office === 'yes' ? this.formData.selected_branches.join(',') : '',
				remark: this.formData.remark || '',
				reservedby: this.currentUser.userId,
				department: this.currentUser.department,
				state: 2 // 默认提交的自动审核通过
			};
			
			// 如果是编辑模式，添加ID
			if (this.isEditMode && this.editId) {
				bookingData.id = this.editId;
			}
			
			const timeRangeText = `${this.selectedTimeRange.start} - ${this.selectedTimeRange.end}`;
			const actionText = this.isEditMode ? '修改' : '预约';
			
			uni.showModal({
				title: `确认${actionText}`,
				content: `确认${actionText}${this.selectedRoom.title}\n时间：${this.selectedDate} ${timeRangeText}`,
				success: async (res) => {
					if (res.confirm) {
						// 显示加载提示
						uni.showLoading({
							title: '提交中...',
							mask: true
						});
						
						try {
							let response;
							if (this.isEditMode && this.editId) {
								// 编辑模式，使用 PUT 请求调用 /system/yuyue 接口更新预约
								response = await api.updateYuyue(bookingData);
							} else {
								// 新增模式，调用新增接口
								response = await api.addYuyue(bookingData);
							}
							
							uni.hideLoading();
							
							if (response && response.code === 200) {
								uni.showToast({
									title: this.isEditMode ? '修改成功' : '预约成功',
									icon: 'success',
									duration: 1500
								});
								
								// 清除编辑数据缓存
								if (this.isEditMode) {
									uni.removeStorageSync('editBookingData');
								}
								
								setTimeout(() => {
									// 关闭当前页面 跳转到我的预约
									uni.redirectTo({
										url: '/pages/my/bookings'
									});
								}, 1500);
							} else {
								uni.showToast({
									title: response.msg || `${actionText}失败，请重试`,
									icon: 'none',
									duration: 2000
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error(`${actionText}预约失败:`, error);
							handleApiError(error);
						}
					}
				}
			});
		}
	}
}
</script>

<style lang="less" scoped>
page {
	background-color: #f5f5f5;
}

.booking-container {
	padding: 30rpx;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	min-height: 100vh;
}

.loading {
	text-align: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 28rpx;
}

.content {
	width: 100%;
}

/* 顶部标题区域 */
.header-section {
	margin-bottom: 30rpx;
}

.header-card {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.header-title {
	flex: 1;
}

.title-text {
	font-size: 48rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.title-subtitle {
	font-size: 24rpx;
	color: #666;
	opacity: 0.8;
}

.header-icon {
	font-size: 60rpx;
	margin-left: 20rpx;
}

/* 表单区域 */
.form-section {
	margin-bottom: 30rpx;
}

.form-card {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.form-item {
	margin-bottom: 40rpx;
	position: relative;
}

.form-item:last-child {
	margin-bottom: 0;
}

.form-label {
	font-size: 30rpx;
	color: #333;
	margin-bottom: 20rpx;
	font-weight: 600;
	display: flex;
	align-items: center;
}

.required {
	color: #ff4757;
	margin-left: 8rpx;
	font-size: 24rpx;
}

.form-input {
	width: 100%;
	height: 90rpx;
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	padding: 0 25rpx;
	font-size: 30rpx;
	background: rgba(255, 255, 255, 0.8);
	box-sizing: border-box;
	transition: all 0.3s ease;
}

.form-input:focus {
	border-color: #2870E5;
	background: rgba(255, 255, 255, 0.95);
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.1);
}

.form-textarea {
	width: 100%;
	min-height: 140rpx;
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	padding: 25rpx;
	font-size: 30rpx;
	background: rgba(255, 255, 255, 0.8);
	box-sizing: border-box;
	resize: none;
	transition: all 0.3s ease;
}

.form-textarea:focus {
	border-color: #2870E5;
	background: rgba(255, 255, 255, 0.95);
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.1);
}

.picker-display {
	width: 100%;
	height: 90rpx;
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	padding: 0 25rpx;
	font-size: 30rpx;
	background: rgba(255, 255, 255, 0.8);
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
	cursor: pointer;
	transition: all 0.3s ease;
}

.picker-display:active {
	background: rgba(255, 255, 255, 0.95);
	transform: scale(0.98);
}

.picker-display.disabled {
	background: rgba(248, 249, 250, 0.8);
	color: #999;
	cursor: not-allowed;
}

.picker-display.disabled:active {
	transform: none;
	background: rgba(248, 249, 250, 0.8);
}

.picker-text {
	color: #333;
	font-weight: 500;
}

.picker-text:empty::before {
	content: '请选择';
	color: #999;
}

.form-display {
	width: 100%;
	height: 90rpx;
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	padding: 0 25rpx;
	font-size: 30rpx;
	background: rgba(248, 249, 250, 0.8);
	box-sizing: border-box;
	display: flex;
	align-items: center;
	color: #666;
}

.display-text {
	color: #666;
	font-weight: 500;
}

/* 时间选择器占位符文字颜色 */
.time-picker-item .picker-text {
	color: #333;
}

.time-picker-item .picker-text.placeholder {
	color: #999;
}

.picker-arrow {
	width: 32rpx;
	height: 32rpx;
	opacity: 0.6;
}



/* 操作按钮区域 */
.action-section {
	margin-bottom: 30rpx;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
}

.action-btn {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
	padding: 30rpx;
	border-radius: 16rpx;
	font-size: 30rpx;
	font-weight: 600;
	transition: all 0.3s ease;
	cursor: pointer;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.action-btn.secondary {
	background: rgba(255, 255, 255, 0.95);
	color: #666;
	border: 2rpx solid #e8eaed;
}

.action-btn.primary {
	background: #2870E5;
	color: #fff;
	box-shadow: 0 8rpx 32rpx rgba(40, 112, 229, 0.3);
}

.action-btn:active {
	transform: scale(0.95);
}

.btn-text {
	font-weight: 600;
}

.btn-icon {
	font-size: 24rpx;
	font-weight: bold;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	backdrop-filter: blur(10rpx);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
	/* 阻止滚动穿透 - iOS专用 */
	overflow: hidden;
	touch-action: none;
	-webkit-overflow-scrolling: none;
	overscroll-behavior: none;
}

.modal-content {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(20rpx);
	border-radius: 20rpx;
	width: 95%;
	max-width: 700rpx;
	max-height: 85vh;
	overflow: hidden;
	box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.2);
	display: flex;
	flex-direction: column;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 40rpx 30rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.modal-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.modal-close {
	font-size: 40rpx;
	color: #999;
	cursor: pointer;
	padding: 10rpx;
	transition: all 0.3s ease;
}

.modal-close:active {
	transform: scale(0.9);
}

.modal-body {
	padding: 30rpx 20rpx;
	max-height: 60vh;
	overflow-y: auto;
	flex: 1;
	/* 优化移动端滚动 - 允许内容区域滚动 */
	-webkit-overflow-scrolling: touch;
	overscroll-behavior: contain;
	/* iOS滚动优化 */
	position: relative;
}

.modal-footer {
	display: flex;
	padding: 30rpx;
	border-top: 2rpx solid #f0f0f0;
	gap: 20rpx;
	flex-shrink: 0;
}

.modal-btn {
	flex: 1;
	text-align: center;
	padding: 25rpx;
	border-radius: 16rpx;
	font-size: 30rpx;
	font-weight: 600;
	transition: all 0.3s ease;
	cursor: pointer;
}

.modal-btn:first-child {
	background: rgba(255, 255, 255, 0.8);
	color: #666;
	border: 2rpx solid #e8eaed;
}

.modal-btn.primary {
	background: #2870E5;
	color: #fff;
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.3);
}

/* 月份选择器样式 */
.month-selector {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;
	padding: 20rpx 15rpx;
	background: rgba(255, 255, 255, 0.8);
	border-radius: 16rpx;
	backdrop-filter: blur(10rpx);
	flex-wrap: wrap;
	gap: 10rpx;
}

.arrow-btn {
	width: 56rpx;
	height: 56rpx;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.3s ease;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	flex-shrink: 0;
}

.arrow-btn:active {
	transform: scale(0.95);
	background: rgba(255, 255, 255, 1);
}

.arrow {
	width: 32rpx;
	height: 32rpx;
	opacity: 0.6;
}

.current-month {
	text-align: center;
	flex: 1;
	min-width: 200rpx;
}

.month-text {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.today-btn {
	background: #2870E5;
	color: #fff;
	padding: 12rpx 20rpx;
	border-radius: 25rpx;
	font-size: 24rpx;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.3s ease;
	flex-shrink: 0;
}

.today-btn:active {
	transform: scale(0.95);
}

/* 日历样式 */
.date-selector {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	width: 100%;
}

.month-header {
	background: rgba(248, 249, 250, 0.8);
	padding: 30rpx 20rpx;
	text-align: center;
	border-bottom: 2rpx solid #e8eaed;
}

.month-display {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.weekdays-header {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	background: rgba(248, 249, 250, 0.8);
	border-bottom: 2rpx solid #e8eaed;
	width: 100%;
}

.weekday {
	padding: 16rpx 8rpx;
	text-align: center;
	font-size: 24rpx;
	color: #666;
	font-weight: 600;
	box-sizing: border-box;
}

.calendar-grid {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	width: 100%;
	/* 确保网格列宽一致 */
	grid-auto-rows: 1fr;
}

.calendar-day {
	/* 使用 padding-bottom 技巧保持正方形（兼容性最好） */
	position: relative;
	width: 100%;
	height: 0;
	padding-bottom: 100%;
	box-sizing: border-box;
	cursor: pointer;
	transition: all 0.3s ease;
	border: 1rpx solid transparent;
	overflow: hidden;
}

.calendar-day .day-number {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1;
}

.calendar-day:active {
	background: rgba(240, 240, 240, 0.5);
}

.calendar-day.other-month {
	color: #ccc;
}

.calendar-day.today {
	background: #FF6B35;
	color: #fff;
	border-radius: 50%;
	box-shadow: 0 4rpx 16rpx rgba(255, 107, 53, 0.3);
}


.calendar-day.today.selected {
	background: #2870E5 !important;
	color: #fff !important;
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.4);
}

.calendar-day.selected {
	background: #2870E5 !important;
	color: #fff !important;
	border-radius: 50%;
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.4);
}


.calendar-day.disabled {
	color: #ccc;
	cursor: not-allowed;
}

.calendar-day.disabled:active {
	background: transparent;
}

.day-number {
	font-size: 28rpx;
	font-weight: 600;
}

.today-dot {
	position: absolute;
	bottom: 8rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 8rpx;
	height: 8rpx;
	background: #fff;
	border-radius: 50%;
	z-index: 2;
}

/* 时间选择器样式 */
.time-picker-container {
	display: flex;
	gap: 20rpx;
}

.time-picker-item {
	flex: 1;
}

.picker-label {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 15rpx;
	font-weight: 500;
}

/* 会议保障选项样式 */
.support-hint {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 20rpx;
	opacity: 0.8;
}

.support-options {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.support-option {
	display: flex;
	align-items: center;
	padding: 30rpx;
	background: rgba(255, 255, 255, 0.8);
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	transition: all 0.3s ease;
	cursor: pointer;
	position: relative;
}

.support-option:active {
	transform: scale(0.98);
}

.support-option.active {
	background: rgba(255, 255, 255, 0.95);
	border-color: #2870E5;
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.1);
}



.option-content {
	flex: 1;
}

.option-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	display: block;
}

.option-check {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.option-check image {
	width: 32rpx;
	height: 32rpx;
	opacity: 0.8;
}

/* 分局选择器样式 */
.select-all-container {
	margin-bottom: 20rpx;
}

.select-all-btn,
.branch-option {
	display: flex;
	align-items: center;
	padding: 30rpx;
	background: rgba(255, 255, 255, 0.8);
	border: 2rpx solid #e8eaed;
	border-radius: 16rpx;
	transition: all 0.3s ease;
	cursor: pointer;
	position: relative;
}

.select-all-btn:active,
.branch-option:active {
	transform: scale(0.98);
}

.select-all-btn.active,
.branch-option.active {
	background: rgba(255, 255, 255, 0.95);
	border-color: #2870E5;
	box-shadow: 0 4rpx 16rpx rgba(40, 112, 229, 0.1);
}

.branch-options {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
}
</style>
